/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import wads.com.AutoDocumentTransaction;
import wads.com.UserInfo;
import wads.com.WADTools;

public class ChangeHtmlToText {
  private String template_ID;
  private Properties transaction_Properties;
  private String transaction_ID;
  private String paramValue ;
  private String currentUser;
  private Vector<String_Write_or_Print> v = new Vector<String_Write_or_Print>();
  private String app_Path = WADTools.APP_PATH;
  private String serverName;
  private Properties prop = new Properties();
  private Vector history = new Vector();
  private String history_string = " ";
  private String Comment_powerUser_title;
  private String orgName;

  public ChangeHtmlToText(String tID, AutoDocumentTransaction adt, String cu){
    currentUser = cu;
    template_ID = tID;
    transaction_Properties = adt.getTransaction_Properties();
    transaction_ID = adt.getTransaction_ID();
    history = adt.getTransaction_History();
    
    try{
      prop.load(new FileInputStream(app_Path+"res/wad_app.properties"));
      orgName = prop.getProperty("orgName", "No");
      serverName = prop.getProperty("ServerName");
    }
    catch(Exception e){
      e.printStackTrace();
    }
    
    try{
      //@deprecated Use InputStreamReader instead for awareness from "char" encoding problem.
      //FileReader fr = new  FileReader(app_Path + "ActiveDocTemplate/"+template_ID+"/"+template_ID+".html");
      File TemplateFile = new File(app_Path+"res/docs/ActiveDocTemplate/"+template_ID+"/"+template_ID+".html");
      InputStreamReader isr = new InputStreamReader(new FileInputStream(TemplateFile), "UTF-8");
      BufferedReader b = new BufferedReader(isr);
      
      String temp;
      while((temp = b.readLine()) != null) {
        String_Write_or_Print st = new String_Write_or_Print();
        st = FilterText(temp, b);
        v.add(st);
      }
      isr.close();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }

  private String_Write_or_Print FilterText(String input, BufferedReader buffer){
    String paramName = null;
    String type;
    String radio_text;
    String option_value;
    String option_text;
    String_Write_or_Print st = new String_Write_or_Print();
    String name_power_User = null;
    String comment_power_User;
    String email_power_User= " ";
    String submit_time;
    if(input.length() > 6){//don't care tag < 6 character
      /*add vector of history from powered users*/

      if(input.compareTo("</form>") == 0){
        for(int i = 0 ; i < this.history.size() ; i++){
          /*call function to seperate power_name : his/her comment*/
          String[] PowerArray = FindPowerNameAndComment(this.history.elementAt(i).toString());
          name_power_User = PowerArray[0];
          comment_power_User = PowerArray[1];
          submit_time = PowerArray[2] +":"+ PowerArray[3] +":"+ PowerArray[4];
          if(name_power_User != null){
            try{
              UserInfo ui;
              File powerUserFile = new File(app_Path+"res/user/PowerUser/"+ orgName);
              ObjectInputStream ois = new ObjectInputStream(new FileInputStream(powerUserFile));
              ui = (UserInfo)ois.readObject();
              for(int a=0; a < ui.getSize(); a++){
                if(ui.getUserDataAt(a).getUsername().equals(name_power_User)){
                  email_power_User = ui.getUserDataAt(a).getEMail();
                }
              }

              this.history_string = this.history_string + "<tr><td width=\"50\"><div align=\"center\">"+ (i+1) +
              "</div></td><td width=\"200\"><div align=\"center\">"+ submit_time +
              "</div></td><td width=\"200\"><div align=\"center\"><a href=mailto:" + email_power_User + ">" +
              name_power_User + "</a>" +
              "</div></td>" + "<td width=\"300\"><div align=\"center\">" + comment_power_User + "</div></td></tr>";
            }
            catch(Exception e) {
              e.printStackTrace();
            }
          }
        }

        this.history_string.concat("</table>");
        st.text = this.history_string;
        st.write_or_print = true; //print
        return st;
      }

      for(int i= 0 ;i < input.length()- 8 ; i++){
        if(input.substring(i,i+7).compareTo("action=") == 0){
          st.text = "<form method=\"post\"  action=\"servlet/manageFlow\">";
          st.write_or_print = false; //write
          return st;
        }

        // filter input
        if(input.substring(i,i+7).compareTo("<input ") == 0){
          /*find paramName from this tag*/
          paramName = findParamName(input);

          /*find type from this tag*/
          for(int j = 0 ;j < input.length()-6 ;j++){
            if(input.substring(j,j+5).compareTo("type=") == 0){
              int start_Type_index = j+7;
              int k = j+7;
              while(input.charAt(k) != '\"')
                k++;
              if(start_Type_index-1 == k)  //same index
                type =  String.valueOf(input.charAt(k));
              else
                type = input.substring(start_Type_index-1,k);

              if(type.compareTo("hidden") == 0){
                st.text = input;
                st.write_or_print = false;//write
                return st;//make tag <input ...> disappear from html
              }
              else if(type.compareTo("image") == 0) {
                st.text = input;
                st.write_or_print = false;//write
                return st;//don't change image
              }
              else if(type.compareTo("radio") == 0) {
                this.paramValue =  this.transaction_Properties.getProperty(paramName);
                radio_text = findRadioText(input, buffer);
                st.text = radio_text;
                st.write_or_print =false;//write
                return st;
              }
              else if(type.compareTo("text") == 0) {
                this.paramValue =  this.transaction_Properties.getProperty(paramName);
                st.text = this.paramValue;
                st.write_or_print = true;//print
                return st;
              }
              else if(type.compareTo("submit") == 0) {
                if(this.history.size() != 0) {
                  Comment_powerUser_title ="Old Comment List:<br>"+
                  "<table border=\"1\"><tr bgcolor=\"#CCFFCC\">"+
                  "<td width=\"50\"><div align=\"center\">Number</div></td>"+
                  "<td width=\"200\"><div align=\"center\">Time Date</div></td>"+
                  "<td width=\"200\"><div align=\"center\">Username</div></td>"+
                  "<td width=\"300\"><div align=\"center\">Comment</div></td></tr>";
                }
                else {
                  Comment_powerUser_title = " ";
                }

                String Addtext_for_Powered_User = WADTools.dupHTMLSpace("<br>", 0, 9)+
                /*"<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"*/
                "<input type=\"radio\" name=\"accept\" value=\"1\">Accept&nbsp;&nbsp;&nbsp;"+
                "<input type=\"radio\" name=\"accept\" value=\"0\">Reject<br>"+
                "Comment:<br><textarea name=\"comment\" cols=\"70\" rows=\"8\"></textarea>"+
                WADTools.dupHTMLSpace("<br>", 9, 0)+
                /*"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>"*/
                "<br><input type=\"submit\" name=\"okbutton\" value=\"Submit\">"+
                "<input type=\"hidden\" name=\"currentUser\" value=\""+this.currentUser+"\">"+
                "<input type=\"hidden\" name=\"transaction_ID\" value=\""+this.transaction_ID+"\">"+
                WADTools.dupHTMLSpace("</form>", 0, 5)+
                /*"</form>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp"*/
                Comment_powerUser_title;

                st.text = Addtext_for_Powered_User;
                st.write_or_print = false;//write
                return st;
              }
              else {
                st.text = " ";
                st.write_or_print = false;//write
                return st;
              }
            }
          }
        }

        //filter select
        if(input.substring(i,i+8).compareTo("<select ") == 0) {
          paramName = findParamName(input);
          this.paramValue =  this.transaction_Properties.getProperty(paramName);
          st.text = " ";
          st.write_or_print = false; //write
          return st;
        }

        if(input.substring(i,i+9).compareTo("</select>") == 0){
          st.text = " ";
          st.write_or_print = false; //write
          return st;
        }

        //filter option
        if(input.substring(i,i+8).compareTo("<option ") == 0){
          //find value same option_Value then find data in that option
          for(int j = 0 ;j < input.length()-6 ;j++){
            if(input.substring(j,j+6).compareTo("value=") == 0){
              //System.out.println("value");
              int start_Value_index = j+8;
              int k = j+8;
              while(input.charAt(k) != '\"')
                k++;
              if(start_Value_index-1 == k)  //same index
                option_value =  String.valueOf(input.charAt(k));
              else
                option_value = input.substring(start_Value_index -1,k);
              //compare option  value with value in select
              if(option_value.compareTo(this.paramValue) == 0){
                //find option data
                option_text = findOptionData(input);
                st.text = option_text;
                st.write_or_print = false; //write
                return st;
              }else
                st.text = " ";
              st.write_or_print = false; //write
              return st;
            }
          }
        }
      }
    }
    
    st.text = input;
    st.write_or_print = false;//write
    return st;
  }

  public String findRadioText(String input, BufferedReader buffer){
    String radio_text = null;
    //String temp; //use for skip next line
     for(int j = 0 ;j < input.length()-6 ;j++){
       if(input.substring(j,j+6).compareTo("value=") == 0){
         int start_text_index = j+8;
         int k = j+8;
         while(input.charAt(k) != '\"')
           k++;
         if(start_text_index-1 == k)  //same index
           radio_text  =  String.valueOf(input.charAt(k));
         else
           radio_text = input.substring(start_text_index -1,k);
         try{
           if(radio_text.compareTo(this.paramValue) == 0){
             return buffer.readLine();
           }
					 else{
             //temp = buffer.readLine(); //skip next line
           }
         }
				 catch(Exception e){
					 e.printStackTrace();
				 }
       }
     }
     return " ";
   }

  private String findOptionData(String input){
    String option_text = null;
    for(int i= 0 ;i < input.length()-8 ; i++){
      if(input.substring(i,i+9).compareTo("</option>") == 0){
        int last_index_text =  i-1;
        int j = i-1;
        while(input.charAt(j) != '>')
          j--;
        if(j+1 == last_index_text){
          option_text =  String.valueOf(input.charAt(j+1));
        }else{
          option_text =  input.substring(j+1,last_index_text);
        }
      }
    }
    return option_text;
  }
  
  private String findParamName(String input){
    String paramName = null;
    for(int j = 0 ;j < input.length()-6 ;j++){
      if(input.substring(j,j+5).compareTo("name=") == 0){
        int start_Name_index = j+7;
        int k = j+7;
        while(input.charAt(k) != '\"')
          k++;
        if(start_Name_index-1 == k){  //same index
          paramName  =  String.valueOf(input.charAt(j+1));
        }else{
          paramName = input.substring(start_Name_index-1,k);
        }
      }
    }
    return paramName;
  }

  public Vector getVector(){
    return v;
  }

  private String[] FindPowerNameAndComment(String NameAndComment){
    String[] Power_NameAndComment = new String[5];
    int i = 0;
    StringTokenizer st = new StringTokenizer(NameAndComment,":");
    while(i < 5){
      Power_NameAndComment[i] = st.nextElement().toString();
      i++;
    }
    return  Power_NameAndComment;
  }
}